const app = getApp();
Page({
  data: {
    StatusBar: app.globalData.StatusBar,
    CustomBar: app.globalData.CustomBar,
    index: 0,
    consume_type:1,
    type_list: [],
    input_str:'',
    disabled:false,
    imgList: [],
    is_login:false,
    topic_info:[],
    publish_cont:'', //留言内容
    uploadUrl:app.api_root+'/api/member/upload_pic',
    detailPics:[],
    community_type:'', //发帖种类
    topic_id:'', //发帖话题
  },

  onLoad:function(e){
    let _this = this,
      topic_id = e.topic_id;
      if(topic_id){
        _this.getTopicInfo(topic_id);
      }
  },

  onShow:function(){
    let _this = this;
    _this.init_Data(); //初始化获取数据
    _this.getTypeList(); //获取分类
    _this.getUserInfo(); //获取账户信息
  },

  //数据初始化
  init_Data:function(){
    let _this = this,
     publish_cont = wx.getStorageSync('publish_cont');
     _this.setData({
      publish_cont:publish_cont
     })
  },

  //获取话题信息
  getTopicInfo:function(topic_id){
    let _this = this;
    app._post('api/index/getTopicInfo', {topic_id:topic_id}, function(result) {
      _this.setData({
        topic_info:result.data,
        topic_id:topic_id
      })
    });
  },

  //获取栏目信息
  getTypeList:function(){
    let _this = this;
    app._post('api/index/getCommunityTypeList', {}, function(result) {
      _this.setData({
        type_list:result.data,
        community_type:result.data[0].community_id
      })
    });
  },

  //获取个人信息
  getUserInfo:function(){
    let _this = this;
    wx.showLoading({
      title: '加载中',
    })
    app._post('api/member/getUserInfo', {}, function(result) {
      wx.hideLoading({})
      if(result.code == 200){
        _this.setData({
          is_login:true,
        })
      }else{
        wx.navigateTo({
          url: '../auth/auth'
        })
      }
    });
  },

  /*表单提交*/
  formSubmit: function() {
    let _this = this,
      publish_cont = _this.data.publish_cont, //发帖内容
      community_type = _this.data.community_type, //发帖栏目
      detailPics = _this.data.detailPics, //发帖配图
      topic_id = _this.data.topic_id; //发帖话题

    // 表单验证
    if (publish_cont == ''){
      app.showError('发布内容不能为空哦~~');
    }

    app._post('api/member/sub_community', {
      community_type:community_type,
      publish_cont:publish_cont,
      detailPics:detailPics,
      topic_id:topic_id
    }, function(result) {
      if(result.code == 200){
        wx.showModal({
          title: '温馨提示',
          content: '发表成功',
          cancelText:'前去看看',
          confirmText:'再发一条',
          success (res) {
            wx.removeStorageSync('publish_cont');
            if (res.confirm) {
              _this.setData({publish_cont:'',topic_id:0})
            } else if (res.cancel) {
              wx.redirectTo({
                url: './index',
              })
            }
          }
        })
      }else{
        app.showError(result.msg);
      }
    });
  },


  //下拉框
  PickerChange: function(e) {
    this.setData({
      index: e.detail.value
    })
  },

  //多行输入框输入
  textareaAInput(e) {
    let _this = this;
    wx.setStorageSync('publish_cont', e.detail.value);
    _this.setData({
      publish_cont: e.detail.value
    })
  },

  //选择图片
  ChooseImage() {
    wx.chooseImage({
      count: 9, //默认9
      sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album'], //从相册选择
      success: (res) => {
        if (this.data.imgList.length != 0) {
          this.setData({
            imgList: this.data.imgList.concat(res.tempFilePaths)
          })
        } else {
          this.setData({
            imgList: res.tempFilePaths
          })
        }
      }
    });
  },

  //多张图片上传
  uploadimg: function(data) {
    var _this = this,
      i = data.i ? data.i : 0,
      success = data.success ? data.success : 0,
      fail = data.fail ? data.fail : 0,
      url = _this.data.uploadUrl,
      path = _this.data.imgList;

    if(_this.data.imgList.length>0){
      wx.showLoading({
        title: '上传中...',
        mask: true,
      })

      wx.uploadFile({
        url: url,
        filePath: path[i],
        name: 'fileData',
        formData: {token:wx.getStorageSync('token')},
        success: (resp) => {
          wx.hideLoading();
          success++;
          var str = resp.data //返回的结果，可能不同项目结果不一样
          var pic = JSON.parse(str);
          var detailPics = _this.data.detailPics;
          detailPics.push(pic.data.img_url)
          _this.setData({
            detailPics: detailPics
          })
        },
        fail: (res) => {
          fail++;
          console.log('fail:' + i + "fail:" + fail);
        },
        complete: () => {
          i++;
          if (i == path.length) { //当图片传完时，停止调用     
            var myEventDetail = {
              picsList: _this.data.detailPics
            }
            var myEventOption = {} // 触发事件的选项
            _this.triggerEvent('myevent', myEventDetail, myEventOption)//结果返回调用的页面
            wx.hideLoading();
            _this.formSubmit();//上传完成，提交
          } else { //若图片还没有传完，则继续调用函数
            data.i = i;
            data.success = success;
            data.fail = fail;
            _this.uploadimg(data);//递归，回调自己
          }
        }
      });
    }else{
      _this.formSubmit();//上传完成，提交
    }
  },

  //点击查看大图
  ViewImage(e) {
    wx.previewImage({
      urls: this.data.imgList,
      current: e.currentTarget.dataset.url
    });
  },

  //删除图片
  DelImg(e) {
    wx.showModal({
      title: '温馨提示',
      content: '确定要删除该照片吗？',
      cancelText: '再看看',
      confirmText: '再见',
      success: res => {
        if (res.confirm) {
          this.data.imgList.splice(e.currentTarget.dataset.index, 1);
          this.setData({
            imgList: this.data.imgList
          })
        }
      }
    })
  },

  //前往话题选择页
  to_topic:function(){
    wx.navigateTo({
      url: './topic'
    })
  },


})